package com.kuafu.latte.transport.server;

import com.kuafu.latte.transport.MessageDecoder;
import com.kuafu.latte.transport.MessageEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyServer {
    private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
    private final int port;
    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workerGroup;
    private final NettyServerJob job;
    private volatile Channel channel; // volatile, please copy reference to use

    public NettyServer(int port,NettyServerJob job) {
        this.port = port;
        this.bossGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors()*2);
        this.workerGroup = new NioEventLoopGroup(4);    // 用来处理已经被接收的连接
        this.job = job;
    }

    public void doStart() throws Exception {
        logger.info("server start, port :{}",port);
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)            // 这里告诉Channel如何接收新的连接
                .childHandler( new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        //获取管道
                        ch.pipeline()//.addLast("logging",new LoggingHandler(LogLevel.INFO))//for debug
                                .addLast("frameDecoder", new LengthFieldBasedFrameDecoder(20*1024, 0, 4, 0, 4))//
                                .addLast("frameEncoder", new LengthFieldPrepender(4))//
                                .addLast("decoder", new MessageDecoder())
                                .addLast("encoder", new MessageEncoder())
                                .addLast("handler", new NettyServerHandler(job));
                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true);
        // 绑定端口，开始接收进来的连接
        ChannelFuture channelFuture = bootstrap.bind(port).sync();
        // 等待服务器socket关闭
        channel = channelFuture.channel();
        logger.info("server started");
    }

    public void doSync() throws Exception{
        try {
            channel.closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public void doClose() throws Exception {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

}